package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.dto.BillUsageVo;
import com.ruoyi.system.domain.vo.AllBillListVo;
import com.ruoyi.system.domain.vo.BillInfoVo;
import com.ruoyi.system.domain.vo.BillListVo;
import com.ruoyi.system.domain.vo.UserInfoByBillInfoIdVo;
import com.ruoyi.system.mapper.BillInfoMapper;
import com.ruoyi.system.service.IBillInfoService;
import com.ruoyi.system.utils.MyMath;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author xy
 * @version 1.0
 * @description:
 * @date 2024/7/4 9:48
 */
@Service
public class BillInfoServiceImpl implements IBillInfoService {
    @Resource
    private BillInfoMapper mapper;

    @Override
    public UserInfoByBillInfoIdVo selectUserEmailByBillInfoId(Long billInfoId) {
        return mapper.selectUserEmailByBillInfoId(billInfoId);
    }

    @Override
    public boolean selectUserLastBillIsPaid(Long userId) {
        Long result = mapper.selectUserLastBillIsPaid(userId);
        return result != null && result > 0;
    }

    @Override
    public BillListVo selectUserLastBillInfo(Long userId) {
        return mapper.selectUserLastBillInfo(userId);
    }

    @Override
    public BillInfoVo selectBillInfo(Long billInfoId) {
        return mapper.selectBillInfo(billInfoId);
    }

    @Override
    public int insertBillInfo(Long userId) {
        // 先查询用户上个月账单是否已经添加成功
        int isInsert = mapper.selectUserIsInsert(userId);
        // 如果已经添加过了，则不需要再次添加
        if (isInsert == 1) {
            return 0;
        }
        // 查询两个月前的用电示数和上个月用电量
        BillUsageVo billUsageDto = mapper.selectBillUsageByUserId(userId);
        // 上上月用电示数
        int lastUsage = billUsageDto.getLastUsage();
        // 上月用电量
        int nowUsage = billUsageDto.getNowUsage();
        // 上月的用电示数
        nowUsage = nowUsage + lastUsage;
        // 上月的电费
        float payAmounts = MyMath.getPayAmount(lastUsage, nowUsage);
        return mapper.insertBillInfo(userId, lastUsage, nowUsage, payAmounts);
    }

    @Override
    public List<BillListVo> selectBillList(Long userId) {
        return mapper.selectBillList(userId);
    }

    @Override
    public List<AllBillListVo> selectAllBillList() {
        return mapper.selectAllBillList();
    }

    @Override
    public int updateBillInfo(Long billInfoId) {
        // 获取当前时间
        LocalDateTime payDateTime = LocalDateTime.now();
        return mapper.updateBillInfo(billInfoId, payDateTime);
    }
}
